{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# pyls_api"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/pyls_api.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/pyls_api.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "#!/usr/bin/env python3\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "class OneVarLns(pywrapcp.BaseLns):\n",
    "  \"\"\"One Var LNS.\"\"\"\n",
    "\n",
    "  def __init__(self, vars):\n",
    "    pywrapcp.BaseLns.__init__(self, vars)\n",
    "    self.__index = 0\n",
    "\n",
    "  def InitFragments(self):\n",
    "    self.__index = 0\n",
    "\n",
    "  def NextFragment(self):\n",
    "    if self.__index < self.Size():\n",
    "      self.AppendToFragment(self.__index)\n",
    "      self.__index += 1\n",
    "      return True\n",
    "    else:\n",
    "      return False\n",
    "\n",
    "\n",
    "class MoveOneVar(pywrapcp.IntVarLocalSearchOperator):\n",
    "  \"\"\"Move one var up or down.\"\"\"\n",
    "\n",
    "  def __init__(self, vars):\n",
    "    pywrapcp.IntVarLocalSearchOperator.__init__(self, vars)\n",
    "    self.__index = 0\n",
    "    self.__up = False\n",
    "\n",
    "  def OneNeighbor(self):\n",
    "    current_value = self.OldValue(self.__index)\n",
    "    if self.__up:\n",
    "      self.SetValue(self.__index, current_value + 1)\n",
    "      self.__index = (self.__index + 1) % self.Size()\n",
    "    else:\n",
    "      self.SetValue(self.__index, current_value - 1)\n",
    "    self.__up = not self.__up\n",
    "    return True\n",
    "\n",
    "  def OnStart(self):\n",
    "    pass\n",
    "\n",
    "  def IsIncremental(self):\n",
    "    return False\n",
    "\n",
    "\n",
    "class SumFilter(pywrapcp.IntVarLocalSearchFilter):\n",
    "  \"\"\"Filter to speed up LS computation.\"\"\"\n",
    "\n",
    "  def __init__(self, vars):\n",
    "    pywrapcp.IntVarLocalSearchFilter.__init__(self, vars)\n",
    "    self.__sum = 0\n",
    "\n",
    "  def OnSynchronize(self, delta):\n",
    "    self.__sum = sum(self.Value(index) for index in range(self.Size()))\n",
    "\n",
    "  def Accept(self, delta, unused_delta_delta, unused_objective_min,\n",
    "             unused_objective_max):\n",
    "    solution_delta = delta.IntVarContainer()\n",
    "    solution_delta_size = solution_delta.Size()\n",
    "    for i in range(solution_delta_size):\n",
    "      if not solution_delta.Element(i).Activated():\n",
    "        return True\n",
    "\n",
    "    new_sum = self.__sum\n",
    "    for i in range(solution_delta_size):\n",
    "      element = solution_delta.Element(i)\n",
    "      int_var = element.Var()\n",
    "      touched_var_index = self.IndexFromVar(int_var)\n",
    "      old_value = self.Value(touched_var_index)\n",
    "      new_value = element.Value()\n",
    "      new_sum += new_value - old_value\n",
    "\n",
    "    return new_sum < self.__sum\n",
    "\n",
    "  def IsIncremental(self):\n",
    "    return False\n",
    "\n",
    "\n",
    "def Solve(type):\n",
    "  solver = pywrapcp.Solver('Solve')\n",
    "  vars = [solver.IntVar(0, 4) for _ in range(4)]\n",
    "  sum_var = solver.Sum(vars).Var()\n",
    "  obj = solver.Minimize(sum_var, 1)\n",
    "  db = solver.Phase(vars, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MAX_VALUE)\n",
    "  ls = None\n",
    "\n",
    "  if type == 0:  # LNS\n",
    "    print('Large Neighborhood Search')\n",
    "    one_var_lns = OneVarLns(vars)\n",
    "    ls_params = solver.LocalSearchPhaseParameters(sum_var, one_var_lns, db)\n",
    "    ls = solver.LocalSearchPhase(vars, db, ls_params)\n",
    "  elif type == 1:  # LS\n",
    "    print('Local Search')\n",
    "    move_one_var = MoveOneVar(vars)\n",
    "    ls_params = solver.LocalSearchPhaseParameters(sum_var, move_one_var, db)\n",
    "    ls = solver.LocalSearchPhase(vars, db, ls_params)\n",
    "  else:\n",
    "    print('Local Search with Filter')\n",
    "    move_one_var = MoveOneVar(vars)\n",
    "    sum_filter = SumFilter(vars)\n",
    "    filter_manager = pywrapcp.LocalSearchFilterManager([sum_filter])\n",
    "    ls_params = solver.LocalSearchPhaseParameters(sum_var, move_one_var, db, None,\n",
    "                                                  filter_manager)\n",
    "    ls = solver.LocalSearchPhase(vars, db, ls_params)\n",
    "\n",
    "  collector = solver.LastSolutionCollector()\n",
    "  collector.Add(vars)\n",
    "  collector.AddObjective(sum_var)\n",
    "  log = solver.SearchLog(1000, obj)\n",
    "  solver.Solve(ls, [collector, obj, log])\n",
    "  print('Objective value = %d' % collector.ObjectiveValue(0))\n",
    "\n",
    "\n",
    "def main():\n",
    "  Solve(0)\n",
    "  Solve(1)\n",
    "  Solve(2)\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
